import React, { useState, useEffect } from 'react';
import { Card, Form, Input, Button, message, InputNumber, TreeSelect, Spin } from 'antd';
import { useNavigate } from 'react-router-dom';
import { createStyles } from 'antd-style';
import { positionAdd } from '@/services/system/postmanagement';
import CustomPageContainer from '@/components/CustomPageContainer';
import { deptpage } from '@/services/system/departmentmanage';
import { useModel } from '@umijs/max';
import axios from 'axios';

const useStyles = createStyles(({ token }) => ({
  container: {
    padding: '24px',
    background: '#f5f5f5',
    minHeight: 'calc(100vh - 48px)',
  },
  card: {
    borderRadius: '8px',
    boxShadow: '0 2px 8px rgba(0, 0, 0, 0.15)',
  },
  formContainer: {
    maxWidth: '800px',
    margin: '0 auto',
    padding: '24px',
  },
  title: {
    fontSize: '16px',
    fontWeight: 'bold',
    color: '#1890ff',
    borderBottom: '2px solid #1890ff',
    paddingBottom: '8px',
    marginBottom: '24px',
  },
  formItem: {
    marginBottom: '16px',
    '& .ant-form-item-label': {
      fontWeight: 500,
      color: '#333',
    },
    '& .ant-input': {
      borderRadius: '4px',
      '&:focus': {
        borderColor: '#1890ff',
        boxShadow: '0 0 0 2px rgba(24, 144, 255, 0.2)',
      },
    },
  },
  buttonGroup: {
    display: 'flex',
    justifyContent: 'center',
    gap: '16px',
    marginTop: '32px',
  },
  button: {
    width: '120px',
    height: '36px',
    borderRadius: '4px',
    fontSize: '14px',
  },
}));

interface DeptTreeItem {
  id: number;
  departmentId: string;
  deptName: string;
  fullName: string;
  deptCategory: number;
  parementId: string | null;
  ancestors: string;
  children?: DeptTreeItem[];
  isDeleted: number;
  remark: string;
  sort: number;
}

interface TreeDataNode {
  title: string;
  value: number | string;
  key: number | string;
  children?: TreeDataNode[];
}

const PostManagementAdd: React.FC = () => {
  const { styles } = useStyles();
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const [deptTreeData, setDeptTreeData] = useState<DeptTreeItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [submitLoading, setSubmitLoading] = useState(false);
  const { institutionId, institutionRoleId } = useModel('auth');

  // 设置 axios 默认超时时间
  axios.defaults.timeout = 30000; // 30秒超时

  useEffect(() => {
    fetchDeptTree();
  }, []);

  const convertToTreeData = (deptList: DeptTreeItem[]): TreeDataNode[] => {
    return deptList.map(dept => ({
      title: dept.deptName,
      value: dept.departmentId,
      key: dept.departmentId,
      children: dept.children ? convertToTreeData(dept.children) : undefined
    }));
  };

  const onFinish = async (values: any) => {
    setSubmitLoading(true);
    try {
      const params = {
        ...values,
        departmentId: values.parementId,
        institutionId: institutionId,
        institutionRoleId: institutionRoleId,
      };
      const response = await positionAdd(params);
      if (response.code === 200) {
        message.success('新增岗位成功');
        navigate('/system/PostManagement');
      } else {
        message.error(response.msg || '新增岗位失败');
      }
    } catch (error) {
      console.error('提交失败:', error);
      message.error('新增岗位失败');
    } finally {
      setSubmitLoading(false);
    }
  };

  const fetchDeptTree = async () => {
    setLoading(true);
    try {
      const response = await deptpage({
        institutionId: institutionId,
        institutionRoleId: institutionRoleId,
      });
      if (response.code === 200 && response.success) {
        setDeptTreeData(response.data);
      } else {
        message.error('获取部门列表失败');
      }
    } catch (error) {
      console.error('获取部门列表失败:', error);
      message.error('获取部门列表失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <CustomPageContainer>
      <div className={styles.container}>
        <Card className={styles.card}>
          <div className={styles.formContainer}>
            <div className={styles.title}>岗位新增</div>
            <Spin spinning={loading}>
              <Form
                form={form}
                layout="vertical"
                onFinish={onFinish}
              >
                <Form.Item
                  label="岗位名称："
                  name="positionName"
                  className={styles.formItem}
                  rules={[{ required: true, message: '请输入岗位名称' }]}
                >
                  <Input placeholder="审核员" />
                </Form.Item>

                <Form.Item
                  label="岗位排序："
                  name="sort"
                  className={styles.formItem}
                  rules={[{ required: true, message: '请输入岗位排序' }]}
                  initialValue={1}
                >
                  <InputNumber min={1} style={{ width: '100%' }} placeholder="1" />
                </Form.Item>

                <Form.Item
                  label="上级部门"
                  name="parementId"
                  className={styles.formItem}
                  rules={[{
                    required: true,
                    message: '请选择上级部门',
                    validator: (_, value) => {
                      if (value === '' || value) {
                        return Promise.resolve();
                      }
                      return Promise.reject(new Error('请选择上级部门'));
                    }
                  }]}
                >
                  <TreeSelect
                    placeholder="请选择上级部门"
                    allowClear
                    showSearch
                    treeDefaultExpandAll
                    style={{ width: '100%' }}
                    dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                    treeData={[
                  
                      ...convertToTreeData(deptTreeData)
                    ]}
                    treeNodeFilterProp="title"
                  />
                </Form.Item>

                <Form.Item
                  label="岗位备注："
                  name="description"
                  className={styles.formItem}
                >
                  <Input.TextArea
                    rows={4}
                    placeholder="该岗位负责部门审核工作。"
                  />
                </Form.Item>

                <div className={styles.buttonGroup}>
                  <Button
                    className={styles.button}
                    onClick={() => navigate('/system/postmanagement')}
                    disabled={loading || submitLoading}
                  >
                    返回
                  </Button>
                  <Button
                    type="primary"
                    htmlType="submit"
                    className={styles.button}
                    loading={submitLoading}
                    disabled={loading}
                  >
                    确定
                  </Button>
                </div>
              </Form>
            </Spin>
          </div>
        </Card>
      </div>
    </CustomPageContainer>
  );
};

export default PostManagementAdd;

